import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:webview_flutter/webview_flutter.dart';
import '../home/dnp_home_tab_controller.dart';
import '../widget/dnp_top_title_widget.dart';
import 'dnp_browser_controller.dart';

class DnpBrowserPage extends StatefulWidget {
  final String path;

  final bool? needBack;

  const DnpBrowserPage({super.key, required this.path, this.needBack});

  @override
  State<DnpBrowserPage> createState() => _DnpBrowserPageState();
}

class _DnpBrowserPageState extends State<DnpBrowserPage> {
  late DnpBrowserController browserController;

  @override
  void initState() {
    super.initState();
    _initBrowserController();
  }

  @override
  void dispose() {
    Get.delete<DnpBrowserController>(tag: widget.path);
    super.dispose();

    Future.delayed(Duration(milliseconds: 300),(){
      if (widget.needBack == true) {
        Get.find<DnpHomeTabController>().onRequestData();
      }
    });
  }

  void _initBrowserController() {
    browserController = Get.put(DnpBrowserController(), tag: widget.path)
      ..ctx = context
      ..request(widget.path);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage("assets/images/ic_base_bg.webp"),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Column(
            children: [_titleWidget(), _progressBarWidget(), SizedBox(height: 6),Expanded(child: _contentWidget())],
          ),
        ),
      ),
    );
  }


  Widget _titleWidget() {
    return GetBuilder<DnpBrowserController>(
        id: "reviseTitle",
        tag: widget.path,
        builder: (controller) {
          return DnpTopTitleWidget(
            titleName: controller.titleName,
            onTap: () {
            },
          );
        });
  }

  Widget _progressBarWidget() {
    return GetBuilder<DnpBrowserController>(
        id: "reviseProgress",
        tag: widget.path,
        builder: (controller) {
          return Visibility(
            visible: controller.progressValue != 1.0 && controller.progressValue != 0.0,
            child: SizedBox(
              height: 3,
              child: LinearProgressIndicator(
                value: controller.progressValue,
                color: Color(0xFF1D4AC8),
              ),
            ),
          );
        });
  }

  Widget _contentWidget() {
    return Expanded(
        child: WebViewWidget(
          controller: browserController.browserController,
        )
    );
  }
}
